package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.Category;
import com.itheima.bean.Dish;
import com.itheima.bean.Setmeal;
import com.itheima.dao.CategoryDao;
import com.itheima.exception.CustomException;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Tang
 * @date 2023/2/21
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 删除分类（当分类下存在套餐或菜品数据时不允许删除）
     * @param categoryId
     */
    @Override
    public void deleteCategory(Long categoryId) {
        //1.查询菜品表（根据分类id查），如果存在菜品，则不能删除
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getCategoryId, categoryId);
        int count = dishService.count(dishWrapper);
        if (count > 0) {
            throw new CustomException("当前分类下存在菜品数据，禁止删除！");
        }

        //2.查询套餐表（根据分类id查），存在套餐数据，则不能删除
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
        setmealWrapper.eq(Setmeal::getCategoryId, categoryId);
        int count1 = setmealService.count(setmealWrapper);
        if (count1 > 0) {
            throw new CustomException("当前分类下存在套餐数据，禁止删除！");
        }

        //3.没有关联的菜品或者套餐，则直接调用父接口的删除方法
        this.removeById(categoryId);
    }
}
